import json
from PySide6 import QtCore
from PySide6.QtCore import Qt, QRegularExpression
from PySide6.QtWidgets import (QWidget, QGroupBox, QHBoxLayout, 
                             QVBoxLayout, QGridLayout)
from qfluentwidgets import CaptionLabel, LineEdit, PushButton
from PySide6.QtGui import QIcon, QRegularExpressionValidator
from core.maocr import maocr
from core.util import is_valid_email, dumpini_user
import setting as c
from core.log import logger

class SFormSignin(QWidget):

    def __init__(self, father):
        super().__init__()
        self.father = father
        self.setWindowIcon(QIcon(c.icon_dir_path))
        self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
        
        self.initUI()
        
        # 计算并设置新窗口的位置
        self.setGeometry(0, 0, 300, 150)
        self.move(father.frameGeometry().topLeft() + father.rect().center() - self.rect().center())
        
     # 绘制界面
    def initUI(self):
        
        self.CreateWindowCommbo()
        
        gridLayout = QGridLayout() 
        gridLayout.addWidget(self.vWinGroupBox, 0, 0, QtCore.Qt.AlignLeft)
        
        # 调用方法绘制界面
        self.setWindowTitle(c.WINTITLE)
        mainLayout = QHBoxLayout()
        mainLayout.addLayout(gridLayout)
        self.setLayout(mainLayout)
        
    def CreateWindowCommbo(self):
        
        self.vWinGroupBox = QGroupBox('sign in')
        self.vWinGroupBox.setMinimumSize(300, 220)
        
    
        regex = QRegularExpression("[A-Za-z0-9@.]{0,32}")
        validator = QRegularExpressionValidator(regex)
        self.email_le = LineEdit()
        self.email_label = CaptionLabel('Email:')
        self.email_le.setPlaceholderText("输入Email")
        self.email_le.setValidator(validator)
        
        regex = QRegularExpression("[A-Za-z0-9.]{0,16}")
        validator = QRegularExpressionValidator(regex)
        self.password_le = LineEdit()
        self.password_label = CaptionLabel('密码:')
        self.password_le.setPlaceholderText("输入密码")
        self.password_le.setValidator(validator)
        self.password_le.setEchoMode(LineEdit.Password) 
        
        
        self.tips_label = CaptionLabel('')
        self.sign_in_btn = PushButton('登录')
        self.sign_in_btn.clicked.connect(self.onclick_sign_in)
        
        self.vBoxLayout = QVBoxLayout(self)
        
        self.hBoxLayout_email = QHBoxLayout()
        self.hBoxLayout_password = QHBoxLayout()
        self.vBoxLayout_signin = QVBoxLayout()
    
        self.initLayout()
    
        self.vWinGroupBox.setLayout(self.vBoxLayout)
        
    def initLayout(self):
        self.hBoxLayout_email.setSpacing(10)
        self.hBoxLayout_email.setContentsMargins(5, 5, 3, 3)
        self.hBoxLayout_email.addWidget(self.email_label, 1)
        self.hBoxLayout_email.addWidget(self.email_le, 4)
        
        self.hBoxLayout_password.setSpacing(10)
        self.hBoxLayout_password.setContentsMargins(5, 5, 3, 3)
        self.hBoxLayout_password.addWidget(self.password_label, 1)
        self.hBoxLayout_password.addWidget(self.password_le, 4)
        
        self.vBoxLayout_signin.setSpacing(10)
        self.vBoxLayout_signin.setContentsMargins(5, 5, 3, 3)
        self.vBoxLayout_signin.addWidget(self.sign_in_btn)
        self.vBoxLayout_signin.addWidget(self.tips_label)
        
        self.vBoxLayout.addLayout(self.hBoxLayout_email)
        self.vBoxLayout.addLayout(self.hBoxLayout_password)
        self.vBoxLayout.addLayout(self.vBoxLayout_signin)
        
    
    def closeEvent(self, event):
            
        # 调用父类的closeEvent方法，确保窗口能够正常关闭
        super().closeEvent(event)

        
    def Reset(self):
        self.email_le.clear()
        self.password_le.clear()
        self.tips_label.clear()
        
    def setTips(self, tips):
        self.tips_label.setText(f"<font color='red'>{tips}</font>")
    
    def onclick_sign_in(self):
        email = self.email_le.text()
        password = self.password_le.text()
        
        self.setTips("")
        if len(email) == 0:
            tips = "请输入Email"
            self.setTips(tips)
            return
        
        if not is_valid_email(email):
            tips = "Email 格式错误"
            self.setTips(tips)
            return
        
        if len(password) < 8:
            tips = "密码至少需要8个字符"
            self.setTips(tips)
            return

        res, ok = maocr.signin(email, password)
        if not ok:
            tips = "网络错误"
            self.setTips(tips)
            return
        info = json.loads(res)
        logger.info(info)
        if info['message'] != "":
            self.setTips(info['message'])
            return
        # QMessageBox.information(self, "消息", "登录成功") 
        dumpini_user(info['username'], info['email'], info['token'], info['invitation'])
        self.father.ResetSignin()
        self.close()